package com.myapp.actions.user;

import com.myapp.entity.Role;
import com.myapp.entity.Uzer;
import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class UpdateUser implements WebAction {

  private Uzer user = new Uzer();

  @Override
  public void prepare(WebRequest request) throws WebException {
    user.setId(request.getLongNN("id"));
    user.setTimeZone(request.getStringNN("timeZone"));
    String[] roles = request.getStringsNN("role");
    for (String string : roles) {
      user.addRoles(Role.valueOf(string));
    }
  }

  @Override
    public EntityManager process(WebRequest req, WebResponse res, EntityManager em) throws Exception {
    Uzer ref = em.getReference(Uzer.class, user.getId());
    ref.setRoles(user.getRoles());
    ref.setTimeZone(user.getTimeZone());
    res.setMessage("Successfully updated user");
    res.setResult(user);
    return em;
  }
}
